// Copyright 2019 orivil.com. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found at https://mit-license.org.

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"regexp"
)

type flag int

const (
	INIT flag = 1 << iota
	INFO
	ERROR
	WARNING
	DANGER
	EMERGENCY
	PANIC
)

func main() {
	err := getImgs("4")
	if err != nil {
		panic(err)
	}
	//err = getImgs("2")
	//if err != nil {
	//	panic(err)
	//}
	//err = getImgs("3")
	//if err != nil {
	//	panic(err)
	//}
}

var imgHost = "http://uploads-admin.cdn.woquhudong.cn/"

var fileNameMatcher = regexp.MustCompile("\\w+\\.\\w+")

func getImgs(page string) error {
	resp, err := http.Get("http://m.tiantianquce.com/index.php/wetest/index/getpagedata/order/top%20desc,utime/rcmd/1/pageIndex/" + page)
	if err != nil {
		return err
	}
	defer resp.Body.Close()
	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	var results []*result
	err = json.Unmarshal(data, &results)
	if err != nil {
		return err
	}
	for _, res := range results {
		if res.Img != "" {
			filename := fileNameMatcher.FindString(res.Img)
			fmt.Println(filename)
			imgRes, err := http.Get(imgHost + res.Img)
			if err != nil {
				return err
			} else {
				err = func() error {
					defer imgRes.Body.Close()
					imgData, err := ioutil.ReadAll(imgRes.Body)
					if err != nil {
						return err
					}
					return ioutil.WriteFile("ad-imgs/"+filename, imgData, os.ModePerm)
				}()
				if err != nil {
					return err
				}
			}
		}
	}
	return nil
}

type result struct {
	Img string `json:"img"`
}
